{% extends "base.html" %}
{% load static %}
{% load i18n %}

{% block title %}{{ title }} | {{ block.super }}{% endblock %}
{% block extra_css %}
<link rel="stylesheet" href="{% static 'daterangepicker/daterangepicker.css' %}">
{% endblock %}
{% block page_title %}{{ title }}{% endblock %}
{% block page_subtitle %}{{ subtitle }}{% endblock %}

{% block breadcrumb %}
<div class="box-tools">
  <div class="btn-group margin-r-5" style="display: none;">
    <button type="button" class="btn btn-default btn-sm dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
      {% for option in metadata.period_options %}
      {% if option.selected %}{{ option.label }}{% endif %}
      {% endfor %}
      <span class="caret"></span>
    </button>
    <ul class="dropdown-menu" role="menu">
      {% for option in metadata.period_options %}
      <li class="{% if option.selected %}active{% endif %}"><a href="#"
          data-value="{{ option.value }}">{{ option.label }}</a></li>
      {% endfor %}
    </ul>
  </div>
  <div class="btn-group margin-r-5" id="reportrange">
    <button type="button" class="btn btn-default btn-sm">
      <i class="fa fa-calendar"></i>&nbsp;
      <span></span>
    </button>
  </div>
  <div class="btn-group">
    <button type="button" class="btn btn-primary btn-sm" id="export-report"><i class="fa fa-download"></i>
      {% trans '导出报告' %}</button>
  </div>
</div>
{% endblock %}

{% block content %}
<div class="row">
  <div class="col-lg-4 col-md-4 col-sm-6">
    <div class="info-box">
      <span class="info-box-icon bg-aqua"><i class="fa fa-users"></i></span>
      <div class="info-box-content">
        <span class="info-box-text">{% trans "租户数" %}</span>
        <span class="info-box-number" id="tenant-kpis-total"></span>
      </div>
    </div>
  </div>
  <div class="col-lg-4 col-md-4 col-sm-6">
    <div class="info-box">
      <span class="info-box-icon bg-green"><i class="fa fa-plus"></i></span>
      <div class="info-box-content">
        <span class="info-box-text">{% trans "新增" %}</span>
        <span class="info-box-number" id="tenant-kpis-new"></span>
        <span class="info-box-text" id="tenant-kpis-new-desc" style="font-size:12px;color:#666;"></span>
      </div>
    </div>
  </div>
  <div class="col-lg-4 col-md-4 col-sm-6">
    <div class="info-box">
      <span class="info-box-icon bg-yellow"><i class="fa fa-heartbeat"></i></span>
      <div class="info-box-content">
        <span class="info-box-text">{% trans "近期活跃" %}</span>
        <span class="info-box-number" id="tenant-kpis-actived"></span>
        <span class="info-box-text" id="tenant-kpis-actived-desc" style="font-size:12px;color:#666;"></span>
      </div>
    </div>
  </div>
</div>

<div class="row">
  <div class="col-md-12">
    <div class="box box-solid">
      <div class="box-header with-border">
        <h3 class="box-title">{% trans "TOP 租户" %}
          <small style="margin-left: 1px;"><a tabindex="0" class="text-muted" data-toggle="popover" data-trigger="focus"
              data-placement="bottom" data-content="{% trans '按租户设备数排序展示，含机柜使用率/空闲率指标。' %}"><i
                class="fa fa-info-circle"></i></a></small>
        </h3>
      </div>
      <div class="box-body">
        <div class="table-responsive">
          <table class="table table-bordered" id="tenant-top-table">
            <thead>
              <tr class="active">
                <th>{% trans '租户' %}</th>
                <th class="text-right">{% trans '设备数' %}</th>
                <th class="text-right">{% trans '机柜数' %}</th>
                <th class="text-right">{% trans '子网' %}</th>
                <th class="text-right">{% trans 'IP地址' %}</th>
                <th class="text-right">{% trans '库存' %}</th>
                <th class="text-right">{% trans '跳线' %}</th>
                <th class="text-right">{% trans '使用率(%)' %}</th>
                <th class="text-right">{% trans '空闲率(%)' %}</th>
              </tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="{% static 'moment/moment.js' %}"></script>
<script src="{% static 'daterangepicker/daterangepicker.js' %}"></script>
<script src="{% static 'js/echarts.min.js' %}"></script>

<script>
  $(function () {
    const baseApiUrl = '{% url "tenant_report_data" %}';
    var start = moment().startOf('quarter')
    var end = moment().endOf('quarter');
    const labelMap = new Map([
      ["最近7天", "week"],
      ["最近30天", "month"],
      ["上周", "last_week"],
      ["上月", "last_month"],
      ["去年", "last_year"],
      ["本周", "this_week"],
      ["本月", "this_month"],
      ["本季度", "this_quarter"],
      ["今年", "this_year"],
      ["全部时间", "all"],
    ]);
    const defaultLabel = "本季度";

    // 全局变量用于存储当前的日期范围
    var currentAggregation = getQueryParam('aggregation') || 'week';
    var currentStart = getQueryParam('start') || start.format('YYYY-MM-DD');
    var currentEnd = getQueryParam('end') || end.format('YYYY-MM-DD');

    function cb(start, end, label) {
      // 更新全局变量
      currentStart = start.format('YYYY-MM-DD');
      currentEnd = end.format('YYYY-MM-DD');

      if (labelMap.has(label)) {
        $("#reportrange span").html(label);
      } else {
        $("#reportrange span").html(start.format("YYYY-MM-DD") + " - " + end.format("YYYY-MM-DD"));
      }
      console.log(`currentAggregation: ${currentAggregation}, currentStart: ${currentStart}, currentEnd: ${currentEnd}`)
      // 刷新数据
      refresh();
    }

    $('#reportrange').daterangepicker({
      startDate: start,
      endDate: end,
      opens: 'auto',
      locale: {
        format: "YYYY-MM-DD",
        separator: " - ",
        applyLabel: "应用",
        cancelLabel: "取消",
        fromLabel: "从",
        toLabel: "至",
        customRangeLabel: "自定义范围",
        weekLabel: "周",
        daysOfWeek: [
          "日",
          "一",
          "二",
          "三",
          "四",
          "五",
          "六"
        ],
        monthNames: [
          "1月",
          "2月",
          "3月",
          "4月",
          "5月",
          "6月",
          "7月",
          "8月",
          "9月",
          "10月",
          "11月",
          "12月"
        ],
        firstDay: 1
      },
      ranges: {
        '最近7天': [moment().subtract(6, 'days'), moment()],
        '最近30天': [moment().subtract(29, 'days'), moment()],
        '上周': [moment().subtract(1, 'week').startOf('week'), moment().subtract(1, 'week').endOf('week')],
        '上月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
        '本周': [moment().startOf('week'), moment().endOf('week')],
        '本月': [moment().startOf('month'), moment().endOf('month')],
        '本季度': [moment().startOf('quarter'), moment().endOf('quarter')],
        '今年': [moment().startOf('year'), moment().endOf('year')],
        '全部时间': [-1, moment().endOf('year')]
      }
    }, cb);

    cb(start, end, defaultLabel);

    // 初始化聚合按钮
    setTimeout(function () {
      setActiveByValue('#aggregation-buttons .agg-btn', currentAggregation, 'data-agg');
    }, 0);

    // 聚合按钮事件
    document.querySelectorAll('.agg-btn').forEach(function (btn) {
      btn.addEventListener('click', function () {
        currentAggregation = this.getAttribute('data-agg');
        setActive(this, '.agg-btn');
        refresh();
      });
    });

    // 下拉菜单事件
    document.querySelectorAll('.dropdown-menu a').forEach(function (item) {
      item.addEventListener('click', function (e) {
        e.preventDefault();
        var dropdownButton = document.querySelector('.btn-group.margin-r-5 button.dropdown-toggle');
        if (dropdownButton) {
          dropdownButton.innerHTML = this.textContent + ' <span class="caret"></span>';
        }
        document.querySelectorAll('.dropdown-menu li').forEach(function (li) { li.classList.remove('active'); });
        this.closest('li').classList.add('active');
        // 注意：这里我们不再使用period参数，而是依赖daterangepicker的回调
      });
    });

    // 导出报告事件
    document.getElementById('export-report').addEventListener('click', function () {
      var url = '{% url "tenant_report_data" %}?aggregation=' + currentAggregation + '&start=' + currentStart + '&end=' + currentEnd;
      window.open(url, '_blank');
    });

    function getQueryParam(key) {
      var params = new URLSearchParams(window.location.search);
      return params.get(key);
    }

    function setActive(element, selector) {
      document.querySelectorAll(selector).forEach(function (b) {
        b.classList.remove('active');
        b.classList.remove('btn-primary');
        b.classList.add('btn-default');
      });
      element.classList.add('active');
      element.classList.remove('btn-default');
      element.classList.add('btn-primary');
    }

    function setActiveByValue(selector, value, attr) {
      var matched = null;
      document.querySelectorAll(selector).forEach(function (b) {
        if (b.getAttribute(attr) === value) {
          matched = b;
        }
      });
      if (matched) {
        setActive(matched, selector);
      }
    }

    function renderChangeBadge(pct) {
      if (pct === null || pct === undefined) {
        return '-';
      }
      var color = 'text-gray';
      var icon = 'fa-minus';
      if (pct > 0) {
        color = 'text-red';
        icon = 'fa-arrow-up';
      } else if (pct < 0) {
        color = 'text-green';
        icon = 'fa-arrow-down';
      }
      return '<span class="' + color + '" style="font-size:12px;"><i class="fa ' + icon + '"></i> ' + pct + '%</span>';
    }

    function refresh() {
      apiUrl = baseApiUrl + '?aggregation=' + currentAggregation + '&start=' + currentStart + '&end=' + currentEnd;
      fetch(apiUrl).then(function (r) { return r.json(); }).then(function (data) {
        renderKpis(data.kpis);
        renderTopTenants(data.top_tenants);
      }).catch(function (err) { console.error('获取报表数据失败:', err); });
    }

    function renderKpis(kpis) {
      var totalEl = document.getElementById('tenant-kpis-total');
      var newEl = document.getElementById('tenant-kpis-new');
      var newDescEl = document.getElementById('tenant-kpis-new-desc');
      var deEl = document.getElementById('tenant-kpis-actived');
      var deDescEl = document.getElementById('tenant-kpis-actived-desc');
      if (totalEl) totalEl.textContent = (kpis && kpis.total) ? kpis.total : 0;
      if (newEl) newEl.textContent = (kpis && kpis.new) ? kpis.new : 0;
      if (newDescEl) newDescEl.innerHTML = renderChangeBadge(kpis ? kpis.new_tenants_percent : null) + ' {% trans "较上期" %}';
      if (deEl) deEl.textContent = (kpis && kpis.actived) ? kpis.actived : 0;
      if (deDescEl) deDescEl.innerHTML = renderChangeBadge(kpis ? kpis.actived_change_percent : null) + ' {% trans "较上期" %}';
    }

    function renderTopTenants(rows) {
      var tbody = document.querySelector('#tenant-top-table tbody');
      if (!tbody) return;
      var data = Array.isArray(rows) ? rows.slice() : [];
      data = data.slice(0, 20);
      var html = [];
      data.forEach(function (item) {
        var t = item.tenant || {};
        var name = t.name || '-';
        var icon = (t.icon_url && t.icon_url.length) ? ('<img src="' + t.icon_url + '" alt="" style="width:18px;height:18px;margin-right:6px;">') : '<i class="fa fa-user-circle-o"></i> ';
        html.push('<tr>' +
          '<td>' + icon + name + '</td>' +
          '<td class="text-right">' + (item.device_count || 0) + '</td>' +
          '<td class="text-right">' + (item.total_racks || 0) + '</td>' +
          '<td class="text-right">' + (item.total_subnet || 0) + '</td>' +
          '<td class="text-right">' + (item.total_ipaddr || 0) + '</td>' +
          '<td class="text-right">' + (item.total_inventory || 0) + '</td>' +
          '<td class="text-right">' + (item.total_cables || 0) + '</td>' +
          '<td class="text-right">' + ((item.avg_utilization || 0).toFixed ? item.avg_utilization.toFixed(2) : item.avg_utilization) + '</td>' +
          '<td class="text-right">' + ((item.free_rate || 0).toFixed ? item.free_rate.toFixed(2) : item.free_rate) + '</td>' +
          '</tr>');
      });
      tbody.innerHTML = html.join('');
    }

    if (window.jQuery && typeof jQuery.fn.popover === 'function') {
      jQuery('[data-toggle="popover"]').popover({ container: 'body' });
    }
    // 打印相关功能
    function ensurePrintStyles() {
      if (document.getElementById('report-print-styles')) return;
      var style = document.createElement('style');
      style.id = 'report-print-styles';
      style.type = 'text/css';
      style.textContent = '@page { size: A4; margin: 10mm; }\n' +
        '@media print {\n' +
        '  .main-header, .main-sidebar, .control-sidebar, .main-footer, .navbar, .sidebar { display: none !important; }\n' +
        '  .content-wrapper, .content { margin: 0 !important; }\n' +
        '  .box { box-shadow: none !important; border: 1px solid #eee !important; }\n' +
        '  .info-box { page-break-inside: avoid; }\n' +
        '  .row { page-break-inside: avoid; }\n' +
        '  table { width: 100% !important; font-size: 12px; }\n' +
        '  #tenant-trend-chart { height: 380px !important; }\n' +
        '  #print-header { text-align: center; margin-bottom: 10px; }\n' +
        '  #print-header h1 { font-size: 24px; margin-bottom: 10px; }\n' +
        '  #print-header p { font-size: 12px; margin: 0; color: #555; }\n' +
        '}';
      document.head.appendChild(style);
    }

    function buildPrintTitle() {
      var header = document.getElementById('print-header');
      if (header && header.parentNode) header.parentNode.removeChild(header);
      var now = new Date();
      var y = now.getFullYear();
      var m = String(now.getMonth() + 1).padStart(2, '0');
      var d = String(now.getDate()).padStart(2, '0');
      var dateStr = y + '-' + m + '-' + d;
      var pageTitle = document.title.split('|')[0].trim();
      var rangeBtn = document.querySelector('.btn-group.margin-r-5 button.dropdown-toggle');
      var rangeText = rangeBtn ? rangeBtn.textContent.replace(/\s*\u25BC?$/, '').trim() : '';
      var aggActive = document.querySelector('#aggregation-buttons .agg-btn.active');
      var aggText = aggActive ? aggActive.textContent.trim() : '';
      var title = dateStr + ' - ' + pageTitle + ' - ' + (rangeText || '');
      var sub = (aggText ? ('聚合: ' + aggText) : '');
      header = document.createElement('div');
      header.id = 'print-header';
      header.innerHTML = '<h1>' + title + '</h1>' + (sub ? ('<p>' + sub + '</p>') : '');
      var content = document.querySelector('.content-wrapper .content') || document.body;
      content.insertBefore(header, content.firstChild);
      return header;
    }

    function optimizeKpiLayout() {
      var firstRow = document.querySelector('.content .row');
      if (!firstRow) return { nodes: [], reset: function () { } };
      var cols = Array.prototype.slice.call(firstRow.querySelectorAll('.info-box')).map(function (box) { return box.closest('[class*="col-"]'); }).filter(Boolean);
      var backup = cols.map(function (c) { return { node: c, style: c.getAttribute('style') }; });
      var n = cols.length || 3;
      var width = (n >= 3) ? '33.3333%' : (n === 2 ? '50%' : '100%');
      cols.forEach(function (c) { c.style.width = width; c.style.float = 'left'; });
      firstRow.style.display = 'block';
      return { nodes: cols, reset: function () { backup.forEach(function (b) { if (b.style === null) b.node.removeAttribute('style'); else b.node.setAttribute('style', b.style); }); firstRow.style.display = ''; } };
    }

    function toImagesAndPrint() {
      ensurePrintStyles();
      var headerNode = buildPrintTitle();
      var kpiReset = optimizeKpiLayout();
      var targets = Array.prototype.slice.call(document.querySelectorAll('[id$="-chart"], .echarts'));
      var backups = [];
      targets.forEach(function (el) {
        if (!window.echarts || !el) return;
        var inst = echarts.getInstanceByDom(el);
        if (!inst) return;
        try { inst.resize(); } catch (e) { }
        var dataURL = inst.getDataURL({ pixelRatio: 2, backgroundColor: '#ffffff' });
        var img = new Image();
        img.src = dataURL;
        img.style.width = (el.clientWidth || 600) + 'px';
        img.style.height = (el.clientHeight || 380) + 'px';
        backups.push({ el: el, img: img, display: el.style.display });
        el.style.display = 'none';
        el.parentNode.insertBefore(img, el.nextSibling);
      });
      function restore() { backups.forEach(function (b) { if (b.img.parentNode) { b.img.parentNode.removeChild(b.img); } b.el.style.display = b.display || ''; }); if (headerNode && headerNode.parentNode) headerNode.parentNode.removeChild(headerNode); if (kpiReset && kpiReset.reset) kpiReset.reset(); }
      var after = function () { restore(); window.removeEventListener('afterprint', after); };
      window.addEventListener('afterprint', after);
      window.print();
    }

    // 为导出按钮添加打印事件
    var btn = document.getElementById('export-report');
    if (btn) {
      // 移除之前的事件监听器，避免冲突
      var newBtn = btn.cloneNode(true);
      btn.parentNode.replaceChild(newBtn, btn);

      newBtn.addEventListener('click', function (e) {
        e.preventDefault();
        e.stopPropagation();
        toImagesAndPrint();
      }, true);
    }

    // 初始加载数据
    // refresh(); 由 daterangepicker 触发
  });
</script>
{% endblock %}